package study.sharding.shardingjdbc.support.key;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * （1）使用 @Component 注解
 * （2）继承 ApplicationContextAware
 * （3）RedisTemplate 必须要 static 修饰
 */
@Slf4j
@Component
public class RedisKeyGenerator implements ShardingKeyGenerator, ApplicationContextAware {

    //auto_increment
    private static final String TYPE = "SEQ";
    /* type定义 */
    private static final String KEY = "ID";
    /* redis client */
    public static RedisTemplate REDIS_TEMPLATE;

    @Getter
    private Properties properties = new Properties();

    @Override
    public Comparable<?> generateKey() {
        ValueOperations valueOp = REDIS_TEMPLATE.opsForValue();
        return valueOp.increment(KEY);
    }

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void setProperties(Properties props) {
        props.forEach((k, v) -> {
            log.info(">>>>>> {}= {}", k, v);
        });
        this.properties = props;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        REDIS_TEMPLATE = context.getBean(StringRedisTemplate.class);
    }
}
